<?php
// 连接到数据库
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "huayuan";

$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}
//获取前端传来的用户id
$user_id = intval($_GET['userId']);
//查询推荐好友recommend_friends
$sql = "SELECT recommend_friends FROM users WHERE user_id = '$user_id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // 输出数据
    while ($row = $result->fetch_assoc()) {
        //将recommend_friends字符串转换为数组
        $recommend_friends = explode(",", $row["recommend_friends"]);
        $my_friends = $row["recommend_friends"];
        //echo $row["recommend_friends"];
        // print_r($recommend_friends);
        //输出数组
        // var_dump($recommend_friends);
        //统计数组元素为""的个数
        $count = 0;
        for ($i = 0; $i < count($recommend_friends); $i++) {
            if ($recommend_friends[$i] == "") {
                $count++;
            }
        }
        //如果$count大于0
        if ($count > 0) {
            //从users表获取user_id和recommend_friends,
            //要求recommend_friends中没有$user_id且字符串长度小于125
            //记录数位$count个，根据online_time排序
            //不能有重复的user_id
            // 去除 my_friends 数组中的空元素
            $my_friends_temp = array_filter(explode(',', $my_friends), function ($id) {
                return !empty($id);
            });
            array_push($my_friends_temp, $user_id);
            $users_str = implode(',', $my_friends_temp);
            // 将处理后的数组转换回字符串
            $sql = "SELECT user_id, recommend_friends FROM users 
            WHERE recommend_friends NOT LIKE '%$user_id%' 
            AND LENGTH(recommend_friends) < 125 
            AND user_id NOT IN ($users_str)
            ORDER BY online_time DESC LIMIT $count";
            $result1 = $conn->query($sql);
            if ($result1->num_rows > 0) {
                // 输出数据
                while ($row1 = $result1->fetch_assoc()) {
                    //获取更新后的recommend_friends
                    $recommend_friends1 = replaceStr($user_id, $row1["recommend_friends"]);
                    //将更新后的recommend_friends插入到users表中
                    // print_r($recommend_friends1);
                    $sql = "UPDATE users SET recommend_friends = '$recommend_friends1' WHERE user_id = '$row1[user_id]'";
                    $conn->query($sql);
                    //更新my_friends
                    $my_friends = replaceStr($row1["user_id"], $my_friends);
                }
                //将更新后的my_friends插入到users表中
                $sql = "UPDATE users SET recommend_friends = '$my_friends' WHERE user_id = '$user_id'";
                $conn->query($sql);
            }
            getRecommend($my_friends, $user_id);
        } else {
            getRecommend($my_friends, $user_id);
        }
    }
}
//定义函数获取返回前端值，json化的二维数组。
function getRecommend($str, $user_id)
{
    //  echo $str;
    //将$str转换为数组
    // print_r($str);
    $recommend_friends = explode(",", $str);
    // print_r($recommend_friends);
    //获取推荐好友的在线时间
    $recommend_friends_time = getLastOnlineTime($str, $user_id);

    // var_dump($recommend_friends_time);
    //获取消息发送时间
    $message_time = getMessageTime($str, $user_id);
    // print_r($message_time);
    //创建一个二维数组
    $arr = array();
    //遍历$recommend_friends
    for ($i = 0; $i < count($recommend_friends); $i++) {
        //如果$recommend_friends[$i]为""
        if ($recommend_friends[$i] != "") {
            $key = sortAndConcatStrings($recommend_friends[$i], $user_id);
            array_push($arr, array(
                $recommend_friends[$i],
                isset($recommend_friends_time[$recommend_friends[$i]]) ? $recommend_friends_time[$recommend_friends[$i]] : "",
                isset($message_time[$key]) ? $message_time[$key] : ""
            ));
        } else {
            array_push($arr, array("", "", ""));
        }
    }
    echo json_encode($arr);
}
//定义函数获取上次在线时间，传入逗号分隔的字符串
function getLastOnlineTime($str, $user_id)
{
    global $conn;
    // Sanitize and validate $str
    $validUserIds = array_filter(explode(',', $str), function ($id) {
        return !empty($id) && is_numeric($id);
    });
    //var_dump($validUserIds);
    if (!empty($validUserIds)) {
        // Join the valid user IDs into a comma-separated string
        $validStr = implode(',', $validUserIds);
        // Use the valid string in the query
        //查询users表，获取user_id和online_time,在$str里的用户。
        $sql = "SELECT user_id, online_time,recommend_friends FROM users WHERE user_id IN ($validStr)";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            // 创建一个空的关联数组
            $userOnlineTimes = array();

            // 遍历查询结果
            while ($row = $result->fetch_assoc()) {
                // 如果 $row['recommend_friends']不包含 $user_id,则将键值赋为"1"
                if (!str_contains($row['recommend_friends'], $user_id)) {
                    $userOnlineTimes[$row['user_id']] = "1";
                } else {
                    // 将 user_id 作为键，online_time 作为值添加到关联数组中
                    $userOnlineTimes[$row['user_id']] = $row['online_time'];
                }
            }
            // var_dump($userOnlineTimes);
            // 返回生成的关联数组
            return $userOnlineTimes;
        }
    }
    // If no valid user IDs, return false
    return [];
}
//定义函数去除空元素。
function removeEmptyElements($tr)
{
    //将$tr转换为数组
    $trarr = explode(",", $tr);
    //遍历$trarr
    $newarr = [];
    for ($i = 0; $i < count($trarr); $i++) {
        //如果$trarr[$i]不为""
        if ($trarr[$i] != "") {
            array_push($newarr, $trarr[$i]);
        }
    }
    //将$newarr转换为字符串
    return implode(",", $newarr);
}
//定义函数获取消息发送时间，传入逗号分隔的字符串
function getMessageTime($str, $user_id)
{
    global $conn;
    //$str转换为数组
    $strarr = explode(",", $str);
    //创建一个数组
    $strarr1 = array();
    //遍历$strarr
    for ($i = 0; $i < count($strarr); $i++) {
        //如果$strarr[$i]为""
        if ($strarr[$i] != "") {
            //将$strarr[$i]插入到$strarr1中
            array_push($strarr1, sortAndConcatStrings($strarr[$i], $user_id));
        }
    }
    //如果数组不为空
    if (!empty($strarr1)) {
        //查询huabu_messages表，获取huabu_id和send_time,在$trarr1里的用户。
        $sql = "SELECT huabu_id, send_time FROM huabu_messages WHERE 
    huabu_id IN ('" . implode("','", $strarr1) . "')";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            // 创建一个空的关联数组
            $messageTimes = array();

            // 遍历查询结果
            while ($row = $result->fetch_assoc()) {
                // 将 huabu_id 作为键，send_time 作为值添加到关联数组中
                $messageTimes[$row['huabu_id']] = $row['send_time'];
            }

            // 返回生成的关联数组
            return $messageTimes;
        }
    }
    return [];
}
//定义函数排序2个字符串，拼接后返回。
function sortAndConcatStrings($str1, $str2)
{
    // 将两个字符串组成数组
    $array = array($str1, $str2);

    // 对数组进行排序
    sort($array);

    // 将排序后的数组元素拼接成一个字符串
    return implode('', $array);
}

//定义函数替换并返回字符串
function replaceStr($str, $arr)
{
    //将$arr转换为数组
    $strarr = explode(",", $arr);
    // echo "strarr";
    // print_r($strarr);
    //遍历$arr
    for ($i = 0; $i < count($strarr); $i++) {
        //如果$arr[$i]为""
        if ($strarr[$i] == "") {
            //将$arr[$i]替换为$str
            $strarr[$i] = $str;
            //将$arr转换为字符串
            //返回字符串
            return implode(",", $strarr);
        }
    }
    return $arr;
}
// 关闭连接
$conn->close();
